export function downloadCSV(
  filename: string,
  columns: { key: string; header: string }[],
  rows: Record<string, unknown>[],
) {
  if (typeof window === "undefined") {
    return;
  }

  const header = columns.map((column) => column.header).join(",");
  const body = rows
    .map((row) =>
      columns
        .map((column) => {
          const value = row[column.key];
          if (value == null) {
            return "";
          }

          const stringValue = String(value).replace(/"/g, '""');
          if (stringValue.search(/([",\n])/g) >= 0) {
            return `"${stringValue}"`;
          }

          return stringValue;
        })
        .join(","),
    )
    .join("\n");

  const csvContent = `${header}\n${body}`;
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);

  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}
